package com.ityj.yygh.hospital.receiver;

import com.ityj.yygh.hospital.service.ScheduleService;
import com.ityj.yygh.model.hosp.Schedule;
import com.ityj.yygh.rabbitmq.constant.RabbitMQConstant;
import com.ityj.yygh.rabbitmq.sercice.RabbitService;
import com.ityj.yygh.vo.order.OrderMqVo;
import com.ityj.yygh.vo.sms.SmsVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class HospitalReceiver {

    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private RabbitService rabbitService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = RabbitMQConstant.QUEUE_ORDER, durable = "true"),
            exchange = @Exchange(value = RabbitMQConstant.EXCHANGE_DIRECT_ORDER),
            key = {RabbitMQConstant.ROUTING_ORDER}
    ))
    public void receiver(OrderMqVo orderMqVo, Message message, Channel channel) {

        Schedule schedule = scheduleService.getScheduleById(orderMqVo.getScheduleId());
        if(null != orderMqVo.getAvailableNumber()) {
            //下单成功更新预约数
            schedule.setReservedNumber(orderMqVo.getReservedNumber());
            schedule.setAvailableNumber(orderMqVo.getAvailableNumber());
        } else {
            //取消预约更新预约数
            int availableNumber = schedule.getAvailableNumber() + 1;
            schedule.setAvailableNumber(availableNumber);
        }
        scheduleService.updateSchedule(schedule);

        // 发送短信
        SmsVo smsVo = orderMqVo.getSmsVo();
        if (smsVo != null) {
            rabbitService.sendMessage(RabbitMQConstant.EXCHANGE_DIRECT_SMS, RabbitMQConstant.ROUTING_SMS_ITEM, smsVo);
        }
    }

}
